//
//  FileTableDelegate.m
//  Wi-Fi Party remade-1
//
//  Created by Vieta Ken on 2021/4/16.
//

#import "FileTableDelegate.h"

@implementation FileTableDelegate

-(void)old_tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    FileTableDataSource *data_source=tableView.dataSource;
    NSString *filename=data_source->files[indexPath.row];
    NSMutableData *song=[[NSMutableData alloc]
                         initWithContentsOfFile: [NSString stringWithFormat:@"%@/%@",data_source->documentPath,data_source->files[indexPath.row] ]
                         ];
    

    Queue *q=[[Queue alloc] init:(int)song.length];
    [room->mixer setTrack:q from:filename];
    [room->mixer addAudioSegment:song.bytes ofSize:(int)song.length from:filename];
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    FileTableDataSource *data_source=tableView.dataSource;
    NSString *nssfilename=[NSString stringWithFormat:@"%@/%@",data_source->documentPath,data_source->files[indexPath.row]];
    const char* filename=[nssfilename cStringUsingEncoding:NSUTF8StringEncoding];
    CFURLRef url=CFURLCreateWithBytes(NULL, (UInt8*)filename, [nssfilename lengthOfBytesUsingEncoding:NSUTF8StringEncoding], kCFStringEncodingUTF8, NULL);
    ExtAudioFileRef song={0};
    UInt32 size=0;
    check_int(ExtAudioFileOpenURL(url, &song), 0, "Failed to open audio file");
    size=sizeof(self->room->stream_format);
    check_int(ExtAudioFileSetProperty(song, kExtAudioFileProperty_ClientDataFormat, size, &(self->room->stream_format)), 0, "Failed to set destination format");
    
    AudioStreamBasicDescription format={0};
    SInt64 song_file_length_frames=0;
    
    size=sizeof(format);
    check_int(ExtAudioFileGetProperty(song, kExtAudioFileProperty_FileDataFormat, &size, &format),0,"Failed to get file format");
    size=sizeof(song_file_length_frames);
    check_int(ExtAudioFileGetProperty(song, kExtAudioFileProperty_FileLengthFrames, &size, &song_file_length_frames), 0, "Failed to get the length of file in frames");
    UInt32 song_file_length_frames_uint32=(UInt32)song_file_length_frames;

    
    AudioBufferList song_buffer_list={0};
    song_buffer_list.mNumberBuffers=1;
    song_buffer_list.mBuffers[0].mNumberChannels=1;
    song_buffer_list.mBuffers[0].mDataByteSize=song_file_length_frames_uint32*self->room->stream_format.mBytesPerFrame;
    song_buffer_list.mBuffers[0].mData=malloc(song_buffer_list.mBuffers[0].mDataByteSize);
    check_int(ExtAudioFileRead(song, &song_file_length_frames_uint32, &song_buffer_list), 0, "Failed to decode the song");
    
    Queue *q=[[Queue alloc] init:song_buffer_list.mBuffers[0].mDataByteSize];
    [room->mixer setTrack:q from:nssfilename];
    [room->mixer addAudioSegment:song_buffer_list.mBuffers[0].mData ofSize:song_buffer_list.mBuffers[0].mDataByteSize from:nssfilename];
}

@end
